
using Qdb.CS.Internal;
using Qdb.CS.Internal.Messages;
using Qdb.Internal;
using Qdb.Internal.Slots;

namespace Qdb.CS.Internal.Messages
{
	public sealed class MWriteNew : MsgObject, IServerSideMessage
	{
		public void ProcessAtServer()
		{
			int classMetadataId = _payLoad.ReadInt();
			LocalObjectContainer container = (LocalObjectContainer)Stream();
			Unmarshall(_payLoad._offset);
			lock (StreamLock())
			{
				ClassMetadata classMetadata = classMetadataId == 0 ? null : container.ClassMetadataForID
					(classMetadataId);
				int id = _payLoad.GetID();
				PrefetchedIDConsumed(id);
				Transaction().SlotFreePointerOnRollback(id);
				Slot slot = container.GetSlot(_payLoad.Length());
				_payLoad.Address(slot.Address());
				Transaction().SlotFreeOnRollback(id, slot);
				if (classMetadata != null)
				{
					classMetadata.AddFieldIndices(_payLoad, null);
				}
				container.WriteNew(Transaction(), _payLoad.Pointer(), classMetadata, _payLoad);
				Transaction().SetPointer(id, slot);
			}
		}

		private void PrefetchedIDConsumed(int id)
		{
			ServerMessageDispatcherImpl serverMessageDispatcher = (ServerMessageDispatcherImpl
				)ServerMessageDispatcher();
			serverMessageDispatcher.PrefetchedIDConsumed(id);
		}
	}
}
